from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET

from . import index_blu


@index_blu.route('/')
@user_login_data
def index():
    """
    显示首页
    1. 如果用户已经登录，将当前登录用户的数据传到模板中，供模板显示
    把右上角的　登陆/注册　切换为　用户头像/退出
    2.新闻主页右侧小框的内容显示
    3.新闻分类
    :return:
    """
    # 1.获取登陆信息
    # user_id = session.get("user_id", None)
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user
    # 2.新闻主页右侧小框的内容显示
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 定义一个空的字典列表，里面装的就是字典
    news_dict_li = []
    for news in news_list:
        # news 是新闻表里一行信息　是个对象
        # news.to_basic_dict()# 把行对象转为行字典，里面存的是｛"id": self.id,"title":title,.....｝
        news_dict_li.append(news.to_basic_dict())
    # 3.新闻分类
    # 查询分类数据，通过模板的形式渲染出来
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_li = []
    for category in categories:
        category_li.append(category.to_dict())
    # data 把要在前段显示的数据都放在一个字典里一起传过去，增加代码的可阅读性
    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "category_li": category_li
    }
    return render_template('news/index.html', data=data)


@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """
    # 1. 获取参数
    # 新闻的分类id
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")
    # 2. 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    filters = [News.status == 0]
    # 查询的不是最新的数据
    if cid != 1:
        # 需要添加条件
        filters.append(News.category_id == cid)
    try:
        # 3. 查询数据
        # 如果是最新数据，不需要分类，只根据时间排序(其他分类也是根据时间分类)，　*filter是拆包
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    # 取到当前页的数据
    news_model_list = paginate.items  # 是个模型对象列表,里面是一个一个模型对象
    total_page = paginate.pages
    current_page = paginate.page
    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    print(news_dict_li)

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }
    return jsonify(errno=RET.OK, errmsg="成功", data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
